package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import jdk.nashorn.internal.ir.annotations.Ignore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@WebFilter("/*")
public class loginFilter implements Filter {
    //路径匹配器
  public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //请求放行
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**" ,
                "/user/login",
                "/user/sendMsg"
        };
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //获取本次url
        String requestURI = req.getRequestURI();
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                //路径匹配成功
                chain.doFilter(req, resp);
                return;
            }
        }
        Employee employee = (Employee) req.getSession().getAttribute("loginEmployee");
        User loginUser = (User) req.getSession().getAttribute("loginUser");
        if (employee != null || loginUser != null) {
            if (employee != null){
                Long id = employee.getId();
                BaseContext.setCurrentId(id);

            }
            if (loginUser != null){
                Long id = loginUser.getId();
                BaseContext.setCurrentId(id);
            }
            //session存在
            chain.doFilter(req, resp);
            BaseContext.release();
        } else {
            resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        }
    }
}
